using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
using System.Text;

namespace Microsoft.PowerShell.CmdletManagement
{
    public class ArrayConverter : IValueConverter
    {
        private delegate T ElementConverter<T>(string input);
        ElementConverter<Int32> intConverter = IntConverter;
        ElementConverter<String> stringConverter = StringConverter;
        private static Int32 IntConverter(string input) { return Int32.Parse(input); }
        private static String StringConverter(string input) { return input; }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                int[] intValues = value as int[];

                if (intValues != null)
                {
                    string[] results = new string[intValues.Length];

                    for (int counter = 0; counter < intValues.Length; counter++)
                        results[counter] = intValues[counter].ToString();

                    return String.Join(", ", results);
                }

                string[] stringValues = value as string[];

                if (stringValues != null)
                {
                    return String.Join(", ", stringValues);
                }
            }

            return string.Empty;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType == Type.GetType("System.Int32[]"))
            {
                return CreateArray<Int32>((string)value, intConverter);
            }
            else if (targetType == Type.GetType("System.String[]"))
            {
                return CreateArray<String>((string)value, stringConverter);
            }
            else
            {
                throw new NotSupportedException("Cannot convert this type.");
            }
        }

        private T[] CreateArray<T>(string input, ElementConverter<T> converter)
        {
            string[] items = input.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            T[] results = new T[items.Length];

            for (int counter = 0; counter < items.Length; counter++)
            {
                results[counter] = converter(items[counter].Trim());
            }

            return results;
        }
    }
}